#!/bin/bash
# $Id: image2ascii 100 2006-10-12 17:21:41Z cmauch $
# 
# Description:  Convert any image to an ASCII-graphic using ImageMagick 
#
# Copyright (C) 2003,2004,2005,2006 Charles Mauch <cmauch@gmail.com>
#               1997,1998,1999,2000,2001,2002 Roland Rosenfeld <roland@spinnaker.de>
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; either version 2 of the License, or (at your option) any later
# version.
# 
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

CONVERT=convert		# The ImageMagick convert binary
PBMTOASCII=pbmtoascii	# The NetPBM pbmtoascii binary

umask 077

tmpdir=${TMPDIR-/tmp}/image2ascii.$$
mkdir $tmpdir || exit 1
trap "rm -rf $tmpdir; exit" 0 1 2 3 15

TMPFILE=$tmpdir/image

usage="Usage: $0 [option] [imagefile]

   -help                display this help text
   -geometry 132x50     define the size of the ascii image"


# set default geometry to display width:
geometry=`stty size </dev/tty | awk '{print $2 "x" $1}'`

# test if stty did not output a useful value:
case "$geometry" in
        0x0 ) geometry=80x24 ;;
        ""  ) geometry=80x24 ;;
esac

case $# in 
        0 ) cat > $TMPFILE ;;
        1 ) case "$1" in
                    -* ) echo "$usage"; exit 0 ;;
                    * )  cat "$1" > $TMPFILE ;;
            esac ;;
        2 ) case "$1" in
                    -geometry ) geometry=$2
                                cat > $TMPFILE ;;
                    * )         echo "$usage"; exit 0 ;;
            esac ;;
        3 ) case "$1" in
                    -geometry ) geometry=$2
                                cat $3 > $TMPFILE ;;
                    * )         echo "$usage"; exit 0 ;;
            esac ;;
        * ) echo "$usage"; exit 0 ;;
esac

# multiply x with 2 and y with 4 (pbmtoascii divides by 2x4)
geometry=`echo $geometry | awk -Fx '{print 2*$1 "x" 4*$2}'`

$CONVERT -geometry $geometry $TMPFILE $TMPFILE.pbm
$PBMTOASCII -2x4 < $TMPFILE.pbm
